package com.xwc.cloud.support.loadbalancer.gateway;

import com.xwc.cloud.support.loadbalancer.LoadbalancerSupportProperties;
import org.springframework.http.HttpCookie;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;

import java.util.List;
import java.util.Objects;

/**
 * 类描述：抽取路由的目标IP信息
 * 作者：徐卫超 (cc)
 * 时间 2022/4/12 10:03
 */
public class DefaultGatewayExtractRouterIp implements ReactiveExtractTargetRouter {

    private final LoadbalancerSupportProperties loadbalancerSupportProperties;

    public DefaultGatewayExtractRouterIp(LoadbalancerSupportProperties loadbalancerSupportProperties) {
        this.loadbalancerSupportProperties = loadbalancerSupportProperties;
    }

    @Override
    public String get(ServerWebExchange exchange) {
        HttpCookie httpCookie = exchange.getRequest().getCookies().getFirst(loadbalancerSupportProperties.getIpRule().getRouterAttrName());
        if (Objects.nonNull(httpCookie)) {
            return httpCookie.getValue();
        }
        List<String> headerValues =
                exchange.getRequest().getHeaders().get(loadbalancerSupportProperties.getIpRule().getRouterAttrName());
        if (!CollectionUtils.isEmpty(headerValues)) {
            return headerValues.stream().findAny().orElse(null);
        } else if (StringUtils.hasText(loadbalancerSupportProperties.getIpRule().getDefaultIp())) {
            return loadbalancerSupportProperties.getIpRule().getDefaultIp();
        }
        return null;
    }
}
